package com.clouddrive.File;

import com.clouddrive.User;
import com.clouddrive.dao.impl.UserServiceImpl;
import com.clouddrive.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@WebServlet(value = "/deletefile",name="DeleteFile")
public class DeleteFile extends HttpServlet {
    User nowUser=new User();
    UserService userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Cookie[] cookies=request.getCookies();
        nowUser=userService.GetUserByCookie(cookies);

        String fs = File.separator;
        String filepath = request.getServletContext().getRealPath("/");
        filepath = filepath.endsWith(fs) ? filepath : filepath + fs;
        filepath += ".." + fs + "upload" + fs + nowUser.getEmail() + fs;
        System.out.println(request.getParameter("deletefilename"));
        try{
            if(!request.getParameter("deletefilename").contains("../")){
                Files.delete(Paths.get(filepath + request.getParameter("deletefilename") + ".Suzuran"));
            }
        } catch (IOException e) {
            System.out.println("删除失败");
            return;
        }
        response.sendRedirect(request.getContextPath() + "/disc.html");
    }
}
